/**
 * @file main.c
 * @brief 运动相机主程序入口
 * @author Your Name
 * @date 2024
 */

#include "action_camera.h"

// 全局系统实例
action_camera_system_t g_camera_system = {0};

// 信号处理函数
void signal_handler(int signum) {
    LOG_INFO("Received signal %d, shutting down...", signum);
    atomic_store(&g_camera_system.sync.system_running, false);
    pthread_cond_broadcast(&g_camera_system.sync.shutdown_cond);
}

// 主消息循环
void main_message_loop(void) {
    message_t msg;
    int ret;
    
    printf("[DEBUG] Main message loop function entered\n");
    LOG_INFO("Main message loop started", 0);
    
    // 检查系统运行标志
    printf("[DEBUG] system_running value: %d\n", atomic_load(&g_camera_system.sync.system_running));
    printf("[DEBUG] Checking main message queue pointer: %p\n", (void *)&g_camera_system.message_queues[THREAD_MAIN]);

    // 检查消息队列结构体的各个字段
    message_queue_t *main_queue = &g_camera_system.message_queues[THREAD_MAIN];
    printf("[DEBUG] Queue messages pointer: %p\n", (void *)main_queue->messages);
    printf("[DEBUG] Queue head: %u\n", main_queue->head);
    printf("[DEBUG] Queue tail: %u\n", main_queue->tail);
    printf("[DEBUG] Queue capacity: %u\n", main_queue->capacity);
    printf("[DEBUG] Queue count: %u\n", main_queue->count);
    
    // 检查互斥锁和条件变量的状态
    printf("[DEBUG] Mutex address: %p\n", (void *)&main_queue->mutex);
    printf("[DEBUG] Not empty condition address: %p\n", (void *)&main_queue->not_empty);
    printf("[DEBUG] Not full condition address: %p\n", (void *)&main_queue->not_full);
    
    // 尝试直接获取和释放互斥锁，测试其是否正常工作
    printf("[DEBUG] Testing mutex lock...\n");
    int mutex_ret = pthread_mutex_lock(&main_queue->mutex);
    printf("[DEBUG] pthread_mutex_lock returned: %d\n", mutex_ret);
    if (mutex_ret == 0) {
        printf("[DEBUG] Testing mutex unlock...\n");
        mutex_ret = pthread_mutex_unlock(&main_queue->mutex);
        printf("[DEBUG] pthread_mutex_unlock returned: %d\n", mutex_ret);
    } else {
        printf("[ERROR] Failed to lock mutex, error: %d\n", mutex_ret);
    }
    
    // 测试条件变量的信号操作
    printf("[DEBUG] Testing condition variables signal...\n");
    pthread_mutex_lock(&main_queue->mutex);
    printf("[DEBUG] Sending signal to not_empty condition...\n");
    int cond_ret = pthread_cond_signal(&main_queue->not_empty);
    printf("[DEBUG] pthread_cond_signal returned: %d\n", cond_ret);
    pthread_mutex_unlock(&main_queue->mutex);
    
    // 避免立即进入message_queue_receive，给信号传播时间
    printf("[DEBUG] Waiting 100ms before calling message_queue_receive...\n");
    
    // 为了更安全，使用简单的循环计数代替clock()函数，避免可能的系统差异
    printf("[DEBUG] Testing simple loop instead of clock()...\n");
    volatile int counter = 0;
    const int loop_count = 10000000; // 大约100ms的循环次数
    for (int i = 0; i < loop_count; i++) {
        counter++; // 防止编译器优化掉循环
        
        // 每100000次循环打印一次状态，确认循环正常进行
        if (i % 1000000 == 0) {
            printf("[DEBUG] Loop progress: %d/%d\n", i, loop_count);
        }
    }
    printf("[DEBUG] Wait completed (counter=%d)\n", counter);
    
    // 在调用message_queue_receive前再次检查队列状态
    printf("[DEBUG] Final queue check before receive - count: %u\n", main_queue->count);
    printf("[DEBUG] Final queue check before receive - messages: %p\n", (void *)main_queue->messages);
    printf("[DEBUG] Final queue check before receive - head: %u\n", main_queue->head);
    printf("[DEBUG] Final queue check before receive - tail: %u\n", main_queue->tail);
    printf("[DEBUG] Final queue check before receive - capacity: %u\n", main_queue->capacity);
    
    // 恢复为无限循环，持续监听消息
    while (atomic_load(&g_camera_system.sync.system_running)) {
        // 处理主线程消息队列
        printf("[DEBUG] Calling message_queue_receive...\n");
        printf("[DEBUG] Before receive - main_queue ptr: %p\n", (void *)main_queue);
        printf("[DEBUG] Before receive - msg ptr: %p\n", (void *)&msg);
        printf("[DEBUG] Before receive - queue count: %u\n", main_queue->count);
        printf("[DEBUG] Before receive - queue messages: %p\n", (void *)main_queue->messages);
        
        // 确保队列结构有效
        if (!main_queue || !main_queue->messages) {
            printf("[ERROR] Invalid message queue structure\n");
            break;
        }
        
        // 确保队列索引有效
        if (main_queue->head >= main_queue->capacity || main_queue->tail >= main_queue->capacity) {
            printf("[ERROR] Invalid queue indices: head=%u, tail=%u, capacity=%u\n", 
                   main_queue->head, main_queue->tail, main_queue->capacity);
            // 重置队列索引
            pthread_mutex_lock(&main_queue->mutex);
            main_queue->head = 0;
            main_queue->tail = 0;
            main_queue->count = 0;
            pthread_mutex_unlock(&main_queue->mutex);
        }
        
        // 检查互斥锁状态
        int mutex_status = pthread_mutex_trylock(&main_queue->mutex);
        if (mutex_status == 0) {
            printf("[DEBUG] Mutex is operational, unlocking...\n");
            pthread_mutex_unlock(&main_queue->mutex);
        } else if (mutex_status != EBUSY) {
            printf("[ERROR] Mutex check failed with code: %d\n", mutex_status);
        }
        
        // 使用无超时模式避免pthread_cond_timedwait的问题
        ret = message_queue_receive(main_queue, &msg, 0);
        printf("[DEBUG] message_queue_receive returned: %d\n", ret);
        
        // 调用后立即检查队列状态
        printf("[DEBUG] After receive - queue count: %u\n", main_queue->count);
        printf("[DEBUG] After receive - queue head: %u\n", main_queue->head);
        printf("[DEBUG] After receive - queue tail: %u\n", main_queue->tail);
        
        if (ret == 0) {
            // 直接使用printf进行调试，不依赖LOG_DEBUG宏
            printf("[DEBUG] Received message: type=%d, source_thread=%d, data_size=%d\n", 
                   msg.type, msg.source_thread, msg.data_size);
            
            // 为所有消息类型添加边界检查
            if (msg.data_size > MAX_MESSAGE_SIZE) {
                printf("[ERROR] Invalid message data_size=%d exceeds MAX_MESSAGE_SIZE=%d\n", 
                       msg.data_size, MAX_MESSAGE_SIZE);
                continue;
            }
            
            switch (msg.type) {
                case MSG_SYSTEM_EVENT:
                    LOG_INFO("System event received from thread %d", msg.source_thread);
                    // 打印系统事件数据内容（如果有）
                    if (msg.data_size > 0) {
                        LOG_DEBUG("System event data size: %d bytes", msg.data_size);
                    }
                    break;
                    
                case MSG_ERROR:
                    // 安全处理MSG_ERROR消息，确保data是有效的以null结尾的字符串
                    LOG_DEBUG("Processing MSG_ERROR: data_size=%d", msg.data_size);
                    if (msg.data_size > 0 && msg.data_size <= MAX_MESSAGE_SIZE) {
                        // 创建一个临时字符串并添加null终止符
                        char error_str[MAX_MESSAGE_SIZE + 1];
                        memset(error_str, 0, sizeof(error_str));
                        memcpy(error_str, msg.data, msg.data_size);
                        error_str[msg.data_size] = '\0';
                        LOG_ERROR("Error message from thread %d: %s", 
                                 msg.source_thread, error_str);
                        // 添加数据十六进制表示用于调试
                        LOG_DEBUG("Error message data (hex): %s", "");
                        for (uint32_t i = 0; i < msg.data_size && i < 32; i++) { // 限制显示前32字节
                            printf("%02x ", (unsigned char)msg.data[i]);
                        }
                        printf("\n");
                    } else {
                        LOG_ERROR("Error message from thread %d: Invalid message data (size=%d)", 
                                 msg.source_thread, msg.data_size);
                    }
                    break;
                    
                case MSG_SHUTDOWN:
                    LOG_INFO("Shutdown message received", 0);
                    atomic_store(&g_camera_system.sync.system_running, false);
                    break;
                    
                default:
                    LOG_DEBUG("Unknown message type: %d, source: %d, size: %d", 
                             msg.type, msg.source_thread, msg.data_size);
                    break;
            }
        } else if (ret != -ETIMEDOUT) {
            // 只有当不是超时错误时才记录日志
            LOG_DEBUG("message_queue_receive returned %d", ret);
            printf("[DEBUG] message_queue_receive returned error code: %d\n", ret);
        } else {
            // 超时错误，无需记录
            printf("[DEBUG] message_queue_receive timed out\n");
        }
        
        // 检查线程健康状态
        if (g_camera_system.threads[THREAD_MONITOR].status == THREAD_RUNNING) {
            // 系统监控线程会处理线程健康检查
        }
        
        // 短暂休眠避免CPU占用过高
        usleep(10000); // 10ms
    }
    
    LOG_INFO("Main message loop ended", 0);
}

// 等待所有线程结束
void wait_for_threads_exit(void) {
    for (int i = 1; i < MAX_THREADS; i++) {
        if (g_camera_system.threads[i].enabled && 
            g_camera_system.threads[i].status != THREAD_TERMINATED) {
            
            LOG_INFO("Waiting for thread %s to exit...", 
                    g_camera_system.threads[i].thread_name);
            
            pthread_join(g_camera_system.threads[i].thread_id, NULL);
            g_camera_system.threads[i].status = THREAD_TERMINATED;
        }
    }
}

/**
 * @brief 主函数
 * @return 程序退出代码
 */
int main(int argc, char* argv[]) {
    // 显式忽略未使用的参数
    (void)argc;
    (void)argv;
    
    int ret = 0;
    
    printf("=== Action Camera System Starting ===\n");
    printf("Version: 1.0.0\n");
    printf("Build Date: %s %s\n", __DATE__, __TIME__);
    printf("=====================================\n");
    
    // 注册信号处理器
    signal(SIGINT, signal_handler);   // Ctrl+C
    signal(SIGTERM, signal_handler);  // 终止信号
    
    // 1. 系统初始化
    LOG_INFO("Initializing system...", 0);
    ret = system_init();
    if (ret != 0) {
        LOG_ERROR("System initialization failed: %d", ret);
        return -1;
    }
    
    // 2. 启动系统
    LOG_INFO("Starting system...", 0);
    ret = system_start();
    if (ret != 0) {
        LOG_ERROR("System start failed: %d", ret);
        system_cleanup();
        return -1;
    }
    
    // 3. 主消息循环
    LOG_INFO("Entering main message loop...", 0);
    main_message_loop();
    
    // 4. 系统关闭
    LOG_INFO("Shutting down system...", 0);
    system_shutdown();
    
    // 5. 等待线程退出
    LOG_INFO("Waiting for threads to exit...", 0);
    wait_for_threads_exit();
    
    // 6. 系统清理
    LOG_INFO("Cleaning up system...", 0);
    system_cleanup();
    
    LOG_INFO("Action Camera System stopped", 0);
    printf("\n=== Action Camera System Stopped ===\n");
    
    return 0;
}